import { getMenus } from '@/mock/index'
import { arrayToTree, sortTreeByField } from '@/utils/tree'
/**
 * 递归过虑菜单
 * @param urls 菜单
 */
function filterPermissionRoutes (urls) {
  const res = []
  urls.forEach(item => {
    // menuType:0目录, 1菜单，2权限
    if (Number(item.menuType) === 0 || Number(item.menuType) === 1) {
      res.push({
        name: item.name,
        uuid: item.uuid,
        path: item.path,
        parentUuid: item.parentUuid,
        menuSort: item.menuSort,
        hidden: item.hidden,
        meta: {
          title: item.title,
          icon: item.icon,
          affix: item.affix
        }
      })
    }
  })

  // 转化成 树
  const resTree = arrayToTree(res)
  return sortTreeByField(resTree, 'menuSort')
}

const state = {
  // 菜单
  permissionRoutes: []
}

const mutations = {
  // 设置左边菜单
  SET_SIDE_MENUS: (state, routers) => {
    state.permissionRoutes = routers
  }
}
const actions = {
  // 生成路由
  async generateRoutes ({ commit }) {
    const res = await getMenus()
    if (res.code === '0000') {
      const urls = res.data
      // 菜单
      const permissionRoutes = filterPermissionRoutes(urls)
      // console.log(permissionRoutes)
      commit('SET_SIDE_MENUS', permissionRoutes)
    }
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
